﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;

namespace Quickuse.Logging.EsLogger
{
    /// <summary>
    /// EsLoggerProvider
    /// </summary>
    internal sealed class EsLoggerProvider : LoggerProvider
    {
        private readonly ConcurrentDictionary<string, EsLogger> _loggers = new ConcurrentDictionary<string, EsLogger>();

        private IEsLoggerSettings _esLoggerSettings;
        private IExternalScopeProvider scopeProvider;

        /// <summary>
        /// EsLoggerProvider
        /// </summary>
        /// <param name="esLoggerSettings">esLoggerSettings</param>
        /// <param name="esLoggerProcessor">esLoggerProcessor</param>
        /// <param name="filter"></param>
        public EsLoggerProvider(IEsLoggerSettings esLoggerSettings, EsLoggerProcessor esLoggerProcessor, Func<string, LogLevel, bool> filter = null)
            :base(esLoggerProcessor.EnqueueMessage, filter)
        {
            if (esLoggerSettings == null)
            {
                throw new ArgumentNullException(nameof(esLoggerSettings));
            }
            _esLoggerSettings = esLoggerSettings;

        }

        /// <summary>
        /// GetScopeProvider
        /// </summary>
        /// <returns></returns>
        private IExternalScopeProvider GetScopeProvider()
        {
            if (_esLoggerSettings.IncludeScopes && scopeProvider == null)
            {
                scopeProvider = new LoggerExternalScopeProvider();
            }
            return _esLoggerSettings.IncludeScopes ? scopeProvider : null;
        }

        /// <summary>
        /// CreateLogger
        /// </summary>
        /// <param name="categoryName">categoryName</param>
        /// <returns></returns>
        public override ILogger CreateLogger(string categoryName)
        {
            return _loggers.GetOrAdd(categoryName, (categoryName1) =>
            {
                return new EsLogger(categoryName1, _esLoggerSettings, LogCallback, Filter, GetScopeProvider());
            });
        }

        /// <summary>
        /// 
        /// </summary>
        public override void Dispose()
        {
            //throw new NotImplementedException();
        }
    }
}
